# @File    : commonUtil.py
# @Project : web_learn
# 通用方法类
import time

from selenium import webdriver
from selenium.webdriver.common.by import By

from common.yamlUtil import YamlUtil


class CommonUtil:

    def __init__(self):
        self.eip_url = YamlUtil("local.yaml").read_yaml()

    # 打开网站方法
    def open_web(self):
        # 浏览器打开会自动关闭解决方法
        options = webdriver.ChromeOptions()
        options.add_experimental_option('detach', True)
        # 打开浏览器
        driver = webdriver.Chrome(options=options)
        # 窗口最大化
        driver.maximize_window()
        # 根据url打开目标网站
        driver.get(f"{self.eip_url['eip_url']}")
        return driver

    # 选择年、月（循环点击→或←按钮直到匹配）
    def select_year_month_component(self, driver, year, month):
        while True:
            # 获取日历中显示的当前年份
            current_year = int(driver.find_element(By.XPATH, "//span[@lay-type='year']").text.strip("年"))
            # 比较当前年份与输入的年份是否相等，不相等则点击箭头进行调整，直至相等后跳出循环
            if current_year > year:
                driver.find_element(By.CLASS_NAME, "laydate-prev-y").click()
            elif current_year < year:
                driver.find_element(By.CLASS_NAME, "laydate-next-y").click()
            else:
                break
            time.sleep(0.5)

        while True:
            # 获取日历中显示的当前月份
            current_month = int(driver.find_element(By.XPATH, "//span[@lay-type='month']").text.strip("月"))
            # 比较当前月份与输入的月份是否相等，不相等则点击箭头进行调整，直至相等后跳出循环
            if current_month > month:
                driver.find_element(By.CLASS_NAME, "laydate-prev-m").click()
            elif current_month < month:
                driver.find_element(By.CLASS_NAME, "laydate-next-m").click()
            else:
                break
            time.sleep(0.5)

    # 选择 时 分 秒
    def select_time_component(self, driver, local, label_text, value_str):
        # zfill(2)表示字符串左边补零（总长度不足两位时即，时间小于10）
        xpath = f"//p[text()='{label_text}']/following-sibling::ol[1]/li[text()='{value_str.zfill(2)}']"
        elem = local.wait_for_element(By.XPATH, xpath)
        # 滚动查找对应时间
        driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", elem)
        elem.click()
